import React, { useEffect, useRef, useState } from "react";
import { Form, Row, Col, Button, Space, Input, message, Spin } from "antd";
import UploadImgX from "../uploadx";
import { changeDrawerState } from "@/store/modules/themeStore";
import { useAppDispatch, useAppSelector } from "@/store/hook.ts";
import { uploadHddInfo, updateHddInfo } from "@/api/api_hdd";
import { changeupdateState } from "@/store/modules/assStore";
const type = "HDD";

interface ChildMethods {
  handleUpload: () => void;
}

function HhdItem({ assInfo }) {
  const isAdd = useAppSelector((state) => state.ass.isAdd);
  const update = useAppSelector((state) => state.ass.update);
  const [form] = Form.useForm();
  useEffect(() => {
    if (!isAdd) {
      const {
        manufacturers,
        cache,
        capacity,
        interfaceSpeed,
        interfaceType,
        rotationalSpeed,
        price,
        score,
      } = assInfo;

      const data = {
        hddManufacturer: manufacturers,
        cache,
        hddCapacity: capacity,
        rotationalSpeed,
        interfaceType,
        interfaceSpeed,
        price,
        score,
      };
      form.setFieldsValue(data);
    } else {
      form.resetFields();
    }
  }, [isAdd, assInfo, form]);
  const HDD = {
    MANUFACTURERS: (
      <Form.Item
        name="hddManufacturer"
        label="HDD厂商"
        rules={[
          {
            required: true,
            message: "Please select your hddManufacturer!",
          },
        ]}
      >
        <Input />
      </Form.Item>
    ),
    CAPACITY: (
      <Form.Item
        name="hddCapacity"
        label="HDD容量"
        rules={[{ required: true, message: "Please input hddCapacity!" }]}
      >
        <Input suffix="GB" />
      </Form.Item>
    ),
    Rotational_Speed: (
      <Form.Item
        name="rotationalSpeed"
        label="转速"
        rules={[{ required: true, message: "Please input rotationalSpeed!" }]}
      >
        <Input suffix="RPM" />
      </Form.Item>
    ),
    CACHE: (
      <Form.Item
        name="cache"
        label="缓存"
        rules={[{ required: true, message: "Please input cache!" }]}
      >
        <Input suffix="MB" />
      </Form.Item>
    ),
    INTERFACE_TYPE: (
      <Form.Item
        name="interfaceType"
        label="接口类型"
        rules={[{ required: true, message: "Please input interfaceType!" }]}
      >
        <Input />
      </Form.Item>
    ),
    INTERFACE_SPEED: (
      <Form.Item
        name="interfaceSpeed"
        label="接口速度"
        rules={[{ required: true, message: "Please input interfaceSpeed!" }]}
      >
        <Input suffix="GB/s" />
      </Form.Item>
    ),
    PRICE: (
      <Form.Item name="price" label="市场估价" rules={[{ required: true }]}>
        <Input prefix="￥" suffix="RMB" />
      </Form.Item>
    ),
    SCORE: (
      <Form.Item
        name="score"
        label="性能评分"
        rules={[{ required: true, message: "Please input score!" }]}
      >
        <Input />
      </Form.Item>
    ),
  };

  const childRef = useRef<ChildMethods>(null); // 创建一个 ref 来引用子组件

  const [spinning, setSpinning] = useState(false);

  const dispatch = useAppDispatch();

  // 表单验证
  const validateMessages = {
    required: "${label} is required!",
    types: {
      email: "${label} is not a valid email!",
      number: "${label} is not a valid number!",
    },
    number: {
      range: "${label} must be between ${min} and ${max}",
    },
  };

  // 表单提交
  const onFinish = async (values: any) => {
    setSpinning(true);
    const img_url_arr = await handleImageUpload();
    handleFormSubmit(values, img_url_arr as string[]);
  };

  //弹窗的状态控制
  const onClose = () => {
    dispatch(changeDrawerState(false));
  };

  //上传图片
  const handleImageUpload = async () => {
    if (childRef.current) {
      const result = childRef.current.handleUpload();
      return result;
    } else {
      return [];
    }
  };

  //添加Center信息
  const handleFormSubmit = async (values: any, img_url_arr: string[]) => {
    try {
      const info = {
        manufacturers: values.hddManufacturer,
        cache: values.cache,
        capacity: values.hddCapacity,
        interfaceSpeed: values.interfaceSpeed,
        interfaceType: values.interfaceType,
        rotationalSpeed: values.rotationalSpeed,
        img_url_arr,
        price: parseFloat(values.price),
        score: parseFloat(values.score),
      };
      if (!isAdd) {
        await updateHddInfo(assInfo._id, info);
        message.success("更新成功");
      } else {
        await uploadHddInfo(info);
        message.success("添加成功");
      }
      setSpinning(false);
      form.resetFields();
      dispatch(changeupdateState(!update));
      dispatch(changeDrawerState(false));
    } catch (error) {
      console.error(error);
      message.error("添加失败，请重试");
    }
  };

  return (
    <>
      <Spin spinning={spinning} fullscreen />
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
        validateMessages={validateMessages}
      >
        {/* 详情图 */}

        <Form.Item>
          <div style={{ fontWeight: "bold", marginBottom: 10 }}>详情图</div>
          <UploadImgX ref={childRef} type={type} />
        </Form.Item>

        {/* GPU主要信息 */}
        <Row gutter={16}>
          <Col span={12}>{HDD.MANUFACTURERS}</Col>
          <Col span={12}>{HDD.CAPACITY}</Col>
          <Col span={12}>{HDD.Rotational_Speed}</Col>
          <Col span={12}>{HDD.CACHE}</Col>
          <Col span={12}>{HDD.INTERFACE_TYPE}</Col>
          <Col span={12}>{HDD.INTERFACE_SPEED}</Col>
          <Col span={12}>{HDD.SCORE}</Col>
          <Col span={12}>{HDD.PRICE}</Col>
        </Row>
        <Form.Item>
          <Space size="large">
            <Button type="primary" danger htmlType="reset" onClick={onClose}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              添加
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </>
  );
}

export default HhdItem;
